package be.kuleuven.mume.beans;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import be.kuleuven.mume.PMF;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable
public class AntwoordBean {
	
//	@NotPersistent
//	private static Logger log = Logger.getLogger(AntwoordBean.class.getName());
	@NotPersistent
	private static final PersistenceManager pm = PMF.get().getPersistenceManager();
	
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key id;
	@Persistent
	private Key fromPersoon;
	@Persistent
	private String text;
	@Persistent
	private Date date;
	@Persistent
	private Key vraag;
	
	public AntwoordBean(PersoonBean fromPersoon, String text, String vraagId){
		//this.fromPersoon = fromPersoon.getId();
		this.text = text;
		this.date = Calendar.getInstance().getTime();
		setVraagId(vraagId);
	}
	public void setId(String key) {
		this.id = KeyFactory.stringToKey(key);
	}
	public String getId() {
		return KeyFactory.keyToString(id);
	}
	public void setFromPersoon(Key fromPersoon) {
		this.fromPersoon = fromPersoon;
	}
	public Key getFromPersoon() {
		return fromPersoon;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getText() {
		return text;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public Date getDate() {
		return date;
	}
	public void setVraagId(String key) {
		this.vraag = KeyFactory.stringToKey(key);
	}
	public String getVraagId() {
		return KeyFactory.keyToString(vraag);
	}
	public String toString(){
		return this.text;
	}
	
	public void store()
	{
		pm.makePersistent(this);
	}
	
	public void delete(){
		pm.deletePersistent(this);
	}
	
	public static class AntwoordBeanFactory{
		public static AntwoordBean getAntwoordById(String antwoordId){
			return pm.getObjectById(AntwoordBean.class, KeyFactory.stringToKey(antwoordId));
		}
		
		@SuppressWarnings("unchecked")
		public static List<AntwoordBean> getAntwoordenForVraag(String vraagId, long page, long rpp){
			Query q = pm.newQuery(AntwoordBean.class);
			q.setRange(page*rpp,(page+1)*rpp);
			q.setFilter("vraag == vraagParam");
			q.setOrdering("date ascending");
			q.declareImports("import com.google.appengine.api.datastore.Key");
			q.declareParameters("Key vraagParam");
			return (List<AntwoordBean>)q.execute(KeyFactory.stringToKey(vraagId));
		}
	}
}
